package com.tyut.dao;

import com.tyut.bean.Student;
import com.tyut.template.DaoTemplate;
import com.tyut.util.QueryRunnerBasic;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class StudentDao implements DaoTemplate<Student> {
    private QueryRunnerBasic qb = new QueryRunnerBasic();
    @Override
    public int add(Student student) {
        String sql = "insert into student(id,name,department,grade,clazz,sex,phone) values(?,?,?,?,?,?,?)";
        qb.insert(sql,new BeanHandler<>(Student.class),
                student.getId(),student.getName(),student.getDepartment(),
                student.getGrade(),student.getClazz(),
                student.getSex(),student.getPhone()
                );
        return 0;
    }

    @Override
    public int delete(Integer id) {
        String sql= "delete from student where id=?";
        int result = 0;
        try {
            result = qb.update(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public int update(Student student) {
        return 0;
    }

    @Override
    public Student query(Integer id) {
        String sql = "select * from student where id=?";
        try {
            return qb.query(sql,new BeanHandler<>(Student.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Student> queryAll() {
        String sql = "select * from student";
        List<Student> list = null;
        try {
            list = qb.query(sql,new BeanListHandler<>(Student.class));
            list.forEach(s-> System.out.println(s));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
